package com.touchealth.test.pdfconverter;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangyanqiang
 * @date 2020/12/15
 **/
public class PDFConverter {


    public static List<String> pdf2Image(File inputStream, String targetLocation, String imageFileNamePrefix) {
        PDDocument document = null;
        List<String> imageFiles = new ArrayList<>(10);
        try {
            long start = System.currentTimeMillis();
            document = PDDocument.load(inputStream);
            int size = document.getNumberOfPages();
            BufferedImage image = null;
            FileOutputStream out = null;
            for (int i = 0; i < size; i++) {
                String fileName = targetLocation+imageFileNamePrefix+"_"+i+".jpg";
                image = new PDFRenderer(document).renderImageWithDPI(i, 130, ImageType.RGB);
                out = new FileOutputStream(targetLocation+imageFileNamePrefix+"_"+i+".jpg");
                ImageIO.write(image, "jpg", out);
                out.close();
                imageFiles.add(fileName);
            }
            long end = System.currentTimeMillis();
            long time = end - start;
            System.out.println("解析pdf为图片 用时:"+time);
        } catch (Exception e) {
            System.out.println("解析文件失败:"+e);
        } finally {
            try {
                if(document != null){
                    document.close();
                }
            } catch (IOException e) {
                System.out.println("关闭文件失败:"+e);
            }
        }
        return imageFiles;
    }


    public static void main(String[] args) throws IOException {

        File pdfFile = new File("/Users/zhangyanqiang/Documents/workspace/self/demo/src/main/java/com/touchealth/test/pdfconverter/发票.pdf");
        InputStream inputStream = new FileInputStream(pdfFile);
        List<String> fileName = pdf2Image(pdfFile, "/Users/zhangyanqiang/Documents/workspace/self/demo/","invoice");
        System.out.println(fileName.get(0));
        inputStream.close();
    }
}
